import React, {
  FC,
  ReactElement,
  useCallback,
  useEffect,
  useReducer,
  useState
} from "react";
import { IState, ITodo, TodoActionType } from "../../types/todo";
import TodoInput from "./component/todo-input";
import TodoList from "./component/todo-list";
import './index.scss';
import todoReducer from "./reducer/todoReducer";
/** 初始化todolist列表 */
function initTodoList(todoList: ITodo[]): IState {
  return {
    todoList: [
      {
        id: new Date().getTime(),
        content: "编写web前端开发流程规范文档",
        completed: false,
      },
    ],
  };
}
const Todo: FC = (): ReactElement => {
  /** 如果一个组件状态很简单，采用下面的勾子函数，否则使用useReducer */
  const [todoList, setTodoList] = useState([]);
  /** state 懒加载*/
  const [state, dispatch] = useReducer(todoReducer, [], initTodoList);
  /** useEffect 等同于类组件中的2个生命周期，可以监听对象的变化然后做出行动 */
  useEffect(() => {
    
  }, []);

  /**
   * 添加待办事项
   * @param todo 待办事项 
   */
  const addTodo = useCallback((todo: ITodo): void => {
      /**
       *  如果不用reducer处理客户端数据的话，当前函数组件会显得
       *  相当的臃肿，因此当组件需要维护自己的状态而不是和其他组件
       *  共享时，我们可以为该组件抽离出一个reducer出来，然后通过
       *  dispatch的方式将业务从组件中解耦出去
       */
      dispatch({
          type:TodoActionType.ADD,
          payload:todo
      })
  },[]);

  /**
   * 从事项列表中移除指定ID的任务
   * @param id 事项的ID
   */
  const removeTodo=useCallback((id:number):void => {
        dispatch({
            type:TodoActionType.REMOVE,
            payload:id
        })
  },[])

  /**
   * 将待办事项状态置为已完成
   * @param id 事项ID
   */
  const completeTodo=useCallback((id:number):void => {
        dispatch({
            type:TodoActionType.COMPLETE,
            payload:id
        })
  },[])

  return (
    <div className="todo">
      <TodoInput todoList={state.todoList} addTodo={addTodo}/>
      <TodoList 
        todoList={state.todoList} 
        removeTodo={removeTodo} 
        completeTodo={completeTodo}
        />
    </div>
  );
};

export default Todo;
